<?php
namespace Weixin\Controller;
use Think\Controller;
class BaseController extends Controller{
    protected $access_token="";
    public function __construct(){
        parent::__construct();
        $this->access_token = $this->getaccess_token();
    }

    public function valid()
    {
        if (!empty($_GET["signature"]) && !empty($_GET["timestamp"]) && !empty($_GET["nonce"]) && !empty($_GET["echostr"])) {
            $signature = $_GET["signature"];
            $timestamp = $_GET["timestamp"];
            $nonce = $_GET["nonce"];
            $echoStr = $_GET["echostr"];
            $token = C('TOKEN');
            $tmpArr = array($token, $timestamp, $nonce);
            sort($tmpArr);//sort（）将数组从小到大排序   rsort()将数组从大到小排序
            $tmpStr = implode($tmpArr);//将数组转化成字符串 implode("|",数组)
            $tmpStr = sha1($tmpStr); //对字符串进行加密

            if ($tmpStr == $signature) {
                echo $echoStr;
                exit;


            }
        }
    }

    /*
     * @param string $url   接口地址
     * @param string $fields post请求传递的参数
     */
    public function curl($url,$fields=""){
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_ENCODING,"utf8");

        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);

        curl_setopt($ch,CURL_TIMEOUT, 30);

        //设置是否是post请求
        if(!empty($fields)){
            curl_setopt($ch,CURLOPT_POST,1); //只要值不为0都是post请求
            curl_setopt($ch,CURLOPT_POSTFIELDS,$fields);
        }

        $res =json_decode(curl_exec($ch),true);


        curl_close($ch);
        return $res;

    }

    /*
     * 获取access_token
     */
    public function getaccess_token(){
        //缓存:文件缓存  内存缓存
        $access_token = "";
        $access_path = "access_token.txt";
        if(is_file($access_path) && file_get_contents($access_path) && filemtime($access_path)+7200>time()){
            $access_token =file_get_contents($access_path);
        }else {
            $appid = C("APPID");
            $secret = C("APPSECRET");
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
            $res = $this->curl($url);
            $access_token = $res["access_token"];
            file_put_contents($access_path, $access_token);
        }
        return $access_token;
    }

    public function clear(){
        $access_token = $this->access_token;
        $url ="https://api.weixin.qq.com/cgi-bin/clear_quota/access_token=$access_token";
        $fields = array(
            "appid"=>C("APPID")
        );
        $res = $this->curl($url,json_encode($fields));
    }
}